﻿package net.wangit.dev.incrementor;

import java.util.List;

import net.wangit.context.ActionContext;
import net.wangit.dev.DomainAction;
import net.wangit.dev.LockUtil;
import net.wangit.dev.VersionUtil;
import net.wangit.dev.version.IncrementorVersion;
import net.wangit.dev.version.Version;
import net.wangit.jdbc.ColumnRow;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.Table;
import net.wangit.jdbc.generator.IncrementorCache;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;


public class SaveIncrementorAction extends DomainAction {

	private static Version version = new IncrementorVersion();

	public SaveIncrementorAction() {
	}

	public void doAction(DB db, ActionContext ac) throws Exception {
		String newId = ac.getRequestParameter("incrementor.iid");
		if (!Checker.isEmpty(newId))
			newId = StringUtil.clearSpace(newId.toLowerCase());
		format(ac, newId);
		super.doAction(db, ac);
		ac.setSessionAttribute(IncrementorUI.KEY, newId);
		String oldId = ac.getRequestParameter("incrementor.iid.k");
		if (!Checker.isEmpty(oldId) && oldId.equals(newId))
			ac.getActionResult().setScript(null);
		IncrementorCache.clear(domain, oldId);
		IncrementorReferenceUtil.update(db, domain, oldId, newId);
		VersionUtil.saveVersion(ac, version, domain, newId);
	}

	private void format(ActionContext ac, String incrementorId) {
		List<Table> tables = ac.getTables();
		if (tables.size() > 0) {
			Table table = tables.get(0);
			List<ColumnRow> rows = table.getRows();
			if (rows.size() > 0) {
				ColumnRow row = rows.get(0);
				row.set("iid", incrementorId);
				LockUtil.setFields(ac, row, "incrementor");
			}
		}
	}

}
